<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="layui/layui.js" charset="utf-8"></script>
    <script src="layui/jquery-3.6.0.min.js" charset="utf-8"></script>
    <script src="layui/layer/layer.js" charset="utf-8"></script>
    <link rel="stylesheet" href="layui/css/layui.css" media="all">
</head>
<body>
<!--
自定义的头部工具栏
-->
<script type="text/html" id="toolbarDemo">
    <div class="layui-btn-container">
        <button class="layui-btn layui-btn-sm" lay-event="add">添加</button>
        <button class="layui-btn layui-btn-sm" lay-event="delete">删除</button>
        <button class="layui-btn layui-btn-sm" lay-event="update">编辑</button>
    </div>
</script>
<script type="text/html" id="user-bar">
    <a class="layui-btn layui-btn-xs" lay-event="edit-user">编辑</a>
</script>
<table id="demo" lay-filter="test"></table>

<script type="text/javascript">
    layui.use(['table','layer','form'], function () {
        var table = layui.table;
         layer = layui.layer;
         form = layui.form;

        //第一个实例
        table.render({
            //   表格要把数据显示到哪个真正的表格上面
            elem: '#demo',
            height: 500,
            toolbar: '#toolbarDemo',
            page: "true",
            limit: 2,  //默认每页要求的数据数量,必须是下面的可选中的一个
            limits: [1, 2, 5, 8, 10], //可选的每页显示的数量
            request: {
                pageName: 'pageNum' //页码的参数名称，默认：page
                , limitName: 'pageSize' //每页数据量的参数名，默认：limit
            }
            , response: {
                statusCode: 1 //规定成功的状态码，默认：0
            },
            parseData: function (res) { //res 即为原始返回的数据
                return {
                    "code": res.code, //解析接口状态
                    "msg": res.msg, //解析提示文本
                    "count": res.data.total, //解析数据长度
                    "data": res.data.list //解析数据列表
                };
            },
            // url: "data.json", //这个表格中的数据来自于什么地方,返回的格式是 json 格式
            url: "/users/users", //这个表格中的数据来自于什么地方,返回的格式是 json 格式
            cols: [[  //表头数据
                {type: "checkbox", title: "选择"},
                {field: "uid", title: "ID", width: 60},
                {field: "uname", title: "姓名", width: 80, sort: "true"},//field 地址返回的 json 数据中哪个 key 的数据显示在这一列
                {field: "usex", title: "性别", width: 60},
                {field: "uemail", title: "邮箱地址", align: "center"},
                {field: "ucode", title: "code"},
                {field: "upassword", title: "密码"},
                {
                    field: "ustatus", title: "状态", templet: function (data) {
                        //返回值就之中显示的效果 ,data 就是当前这一行要显示的数据的 json
                        //  console.log(data)
                        var ustatus = data.ustatus;
                        if (ustatus == 0) {
                            return '停用'
                        } else if (ustatus == 1) {
                            return '启用'
                        }
                    }
                },
                { title: "操作",toolbar:"#user-bar"}
            ]]

        });


        table.on('toolbar(test)', function (obj) {
            //test 是因为我们的 table 中有一个 lay-filter 的值是 test
            //console.log(obj)
            var checkStatus = table.checkStatus(obj.config.id);// 获取到了当前选中的数据
          //  console.log(checkStatus);
            switch (obj.event) {
                case 'add':
                  //  alert("添加执行了");
                    openwindow(null);
                    break;
                case 'update':
                    //alert("更新执行了");
                    if (checkStatus.data.length != 1) {
                        alert("更新只能更新一条数据")
                    }else{
                        openwindow(checkStatus.data[0]);//传递具体的当前的这一行数据过去
                    }
                    break;
                case 'delete':
                   // alert("删除执行了");
                    var xuanzhongdeshuju = checkStatus.data;
                    var params = '';
                    if (xuanzhongdeshuju) {
                        for (var i = 0; i < xuanzhongdeshuju.length; i++) {
                            var uid = xuanzhongdeshuju[i].uid;
                            console.log(uid);
                            if (i == 0) {
                                params += "?ids=" + uid;
                                continue;
                            }
                            // if (i == xuanzhongdeshuju.length - 1) {
                            //     params += "ids=" + uid;
                            //     continue;
                            // }
                            if (i != 0) {
                                params += "&ids=" + uid;
                                continue;
                            }

                        }
                        //发请求
                        //?uid=1&uid=2&uid=3
                        $.ajax({
                            url: "/users/users"+params,
                            type:"DELETE",
                            success:function (res){
                                if (res && res.code == 1) {
                                    alert("删除成功");
                                    //更新表格
                                    table.reload("demo",{})
                                }else{
                                    alert(res.msg);
                                }
                            },
                        })
                    }
                    break;
            }
        })

        table.on('tool(test)',function (obj){
            switch (obj.event) {
                case "edit-user":
                    openwindow(obj.data)
                    break;
            }
        })
    });


    function openwindow(data){
        layer.open({
            type: 1,
            title:"编辑",
            btn:['确定','取消'],
            yes: function (index, layero){
                //alert("你尿床怎么了? 这么大人尿床你居然还问怎么了? 是不是得去医院看看泌尿科")
                //需要确定现在是添加还是更新
                $.ajax({
                    url: data==null?'/users/user':'更新',
                    method: "POST",
                    contentType: 'application/json;charset=utf-8',
                    data: data == null ?JSON.stringify($("#user-add-from").serializeJson()):JSON.stringify($("#user-edit-from").serializeJson()),
                    success: function (res){
                        if (res.code == 1) {
                            alert("操作成功");
                        }else{
                            alert(res.msg);
                        }
                        layer.close(index)
                    }

                })
            },
            content: data==null?$('#user-add-layer').html():$('#user-edit-layer').html(),
            success: function (){
                form.render();
                if (data) {
                    form.val("user-edit-from",data);
                }
            }

        })
    }



    //自定义函数
    $.fn.serializeJson = function () {
        var serializeObj = {};
        var array = this.serializeArray();
        $.each(array, function () {
            if (serializeObj[this.name] !== undefined) {
                if (!serializeObj[this.name].push) {
                    serializeObj[this.name] = [serializeObj[this.name]];
                }
                serializeObj[this.name].push(this.value || '');
            } else {
                serializeObj[this.name] = this.value || '';
            }
        });
        return serializeObj;
    };
</script>






<script type="text/html" id="user-add-layer">

    <form class="layui-form" action="" lay-filter="user-add-from" id="user-add-from">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="uname" lay-verify="title" autocomplete="off" placeholder="请输入姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="uemail" lay-verify="required" lay-reqtext="邮箱必须输入？" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="text" name="usex" lay-verify="required"  placeholder="请输入性别" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="text" name="upassword" lay-verify="required"  placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>

</script>

<script type="text/html" id="user-edit-layer">

    <form class="layui-form" action="" lay-filter="user-edit-from" id="user-edit-from">
        <input type="hidden" name="uid">
        <div class="layui-form-item">
            <label class="layui-form-label">姓名</label>
            <div class="layui-input-block">
                <input type="text" name="uname" lay-verify="title" autocomplete="off" placeholder="请输入姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">邮箱</label>
            <div class="layui-input-block">
                <input type="text" name="uemail" lay-verify="required" lay-reqtext="邮箱必须输入？" placeholder="请输入邮箱" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">性别</label>
            <div class="layui-input-block">
                <input type="text" name="usex" lay-verify="required"  placeholder="请输入性别" autocomplete="off" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">密码</label>
            <div class="layui-input-block">
                <input type="text" name="upassword" lay-verify="required"  placeholder="请输入密码" autocomplete="off" class="layui-input">
            </div>
        </div>
    </form>

</script>



</body>
</html>